package com.ctlele.team.space.activity.impl;

import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.SeekBar;
import android.widget.TextView;

import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;

import com.ctlele.team.space.R;
import com.ctlele.team.space.widget.view.VodPlayerUI;
import com.tencent.rtmp.ITXVodPlayListener;
import com.tencent.rtmp.TXLiveConstants;
import com.tencent.rtmp.TXVodPlayer;
import com.tencent.rtmp.ui.TXCloudVideoView;

public class TXCVodPlayerActivity extends AppCompatActivity {

    private static final String TAG = "TXCVodPlayerActivity";

    public static final String URL_KEY = "url";

    public static final String CONVERT_KEY = "convert";

    public static final String VIDEO_TITLE_KEY = "video_title";

    TXCloudVideoView mPlayerView;

    TXVodPlayer mVodPlayer;

    VodPlayerUI mVodPlayerUI;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_txc_vod_player);

        String url = getIntent().getStringExtra(URL_KEY);
        String convert = getIntent().getStringExtra(CONVERT_KEY);
        String videoTitle = getIntent().getStringExtra(VIDEO_TITLE_KEY);

        if (TextUtils.isEmpty(url) || !url.startsWith("http")) onBackPressed();

        mPlayerView = findViewById(R.id.video_view);
        mVodPlayer = new TXVodPlayer(this);
        mVodPlayer.setPlayerView(mPlayerView);
        mVodPlayerUI = findViewById(R.id.player_ui);

        mVodPlayer.setRenderMode(TXLiveConstants.RENDER_MODE_ADJUST_RESOLUTION);

        mVodPlayer.setAutoPlay(false);
        mVodPlayer.startVodPlay(url);

        mVodPlayerUI.setController(new VodPlayerUI.IVodPlayController() {
            @Override
            public void play() {
                mVodPlayer.resume();
            }

            @Override
            public void pause() {
                mVodPlayer.pause();
            }

            @Override
            public void stop() {

            }

            @Override
            public void resume() {
                mVodPlayer.resume();
            }

            @Override
            public void seek(long time) {
                // TODO: seek方法不太好用
                mVodPlayer.seek(time);
            }

            @Override
            public void playWithTime(long time) {
            }

            @Override
            public void playWithTime(float time) {
                mVodPlayer.stopPlay(false);
                mVodPlayer.setStartTime(time);
                mVodPlayer.startVodPlay(url);
                mVodPlayer.resume();
            }

            @Override
            public void fullScreen() {
                // TODO: 全屏播放
                toFullScreen();
            }

            @Override
            public void unFullScreen() {
                // TODO: 取消全屏
                toUnFullScreen();
            }
        });

        // 加载封面图
        if (!TextUtils.isEmpty(convert)) mVodPlayerUI.setConvertPicture(convert);
        mVodPlayerUI.setVideoTitle(videoTitle);
        // if (!TextUtils.isEmpty(convert)) Picasso.with(this).load(convert).into(mConvertImg);
        mVodPlayerUI.setOnBackPressed((view) -> onBackPressed());

        mPlayerView.setOnClickListener(item -> {
            if (mVodPlayerUI.getVisibility() == View.GONE) {
                mVodPlayerUI.setVisibility(View.VISIBLE);
            } else {
                mVodPlayerUI.setVisibility(View.GONE);
            }
        });

        SeekBar videoSeekBar = mVodPlayerUI.getVideoSeekBar();
        TextView currTime = mVodPlayerUI.getCurrTime();
        TextView totalTime = mVodPlayerUI.getTotalTime();
        mVodPlayer.setVodListener(new ITXVodPlayListener() {
            @Override
            public void onPlayEvent(TXVodPlayer player, int event, Bundle param) {
                switch (event) {
                    case TXLiveConstants.PLAY_EVT_PLAY_END:
                        mVodPlayerUI.setVisibility(View.VISIBLE);
                        mVodPlayerUI.end();
                        return;
                    case TXLiveConstants.PLAY_EVT_PLAY_PROGRESS:
                        // 视频总长, 单位是毫秒
                        int totalMs = param.getInt(TXLiveConstants.EVT_PLAY_DURATION_MS);
                        // 播放进度, 单位是毫秒
                        int currMs = param.getInt(TXLiveConstants.EVT_PLAY_PROGRESS_MS);
                        mVodPlayerUI.setTotalMs(totalMs);
                        videoSeekBar.setProgress(calPercent(currMs, totalMs));
                        currTime.setText(formatMilliseconds(currMs));
                        totalTime.setText(formatMilliseconds(totalMs));
                        return;
                }
            }

            @Override
            public void onNetStatus(TXVodPlayer player, Bundle bundle) {
            }
        });

    }

    void toFullScreen() {
        // 隐藏状态栏和导航栏
        View decorView = getWindow().getDecorView();
        int uiOptions = View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION;
        decorView.setSystemUiVisibility(uiOptions);
        // 设置横屏显示
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
        // 隐藏ActionBar
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.hide();
        }
    }

    void toUnFullScreen() {
        // 还原为竖屏显示
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED);
        // 显示状态栏和导航栏
        View decorView = getWindow().getDecorView();
        int uiOptions = View.SYSTEM_UI_FLAG_VISIBLE;
        decorView.setSystemUiVisibility(uiOptions);
        // 显示ActionBar
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.show();
        }

    }

    public static int calPercent(int subtotal, int total) {
        if (total == 0) {
            return 0;
        }
        double percentage = (double) subtotal / total * 100;
        return (int) Math.round(percentage);
    }

    public static String formatMilliseconds(int milliseconds) {
        int seconds = (milliseconds / 1000) % 60;
        int minutes = (milliseconds / (1000 * 60)) % 60;
        int hours = (milliseconds / (1000 * 60 * 60)) % 24;
        return String.format("%02d:%02d:%02d", hours, minutes, seconds);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mVodPlayer.stopPlay(true);
        mPlayerView.onDestroy();
    }
}